package com.woniuxy.main.handler;

import java.io.IOException;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import org.springframework.web.bind.annotation.RestController;

import com.woniuxy.main.util.WebSocketUtil;


/**
 * 处理请求
 * 
 * @author Administrator
 *
 */
@RestController
@ServerEndpoint("/ChatHandler/{uname}")   //默认支持stomp协议
public class ChatHandler {
	
	@OnOpen		//建立起连接
	public void openSession(@PathParam("uname") String uname,Session session) {
		String message = uname+" 你好，我是"+uname;
		//将当前用户放入群里面
		WebSocketUtil.SESSIONMAP.put(uname, session);
		//向所有人发送消息
		WebSocketUtil.sendAll(message);
	}
	
	@OnMessage 	//接收到消息时
	public void onMessage(@PathParam("uname") String uname,String message){
		message = uname+" "+message;
		WebSocketUtil.sendAll(message);
	}
	
	@OnClose	//离开聊天室
	public void onClose(@PathParam("uname") String uname,Session session){
		//将当前用户注销
		WebSocketUtil.SESSIONMAP.remove(uname);
		//群发
		//WebSocketUtil.sendAll("用户："+uname+"离开聊天室");
		//关闭session
		try {
			session.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	//连接时出现异常
	public void onErrop(Session session,Throwable throwable){
		//关闭session
				try {
					session.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
	}
	
}
